package com.ycfmedical.bed.wifi;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;

import com.ycfmedical.bed.Constants;
import com.ycfmedical.bed.service.VitalSignService;
import com.ycfmedical.bed.utils.ConvertOrderCheckoutUtil;
import com.ycfmedical.bed.utils.OrderMsgExecute;
import com.ycfmedical.bed.utils.RefreshDataUtils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

import cn.droidlover.xdroidmvp.event.BusProvider;
import cn.droidlover.xdroidmvp.log.XLog;

/**
 * Created by Administrator on 2017-03-27.
 */

public class ClientThread extends Thread {

    private OutputStream outputStream = null;
    private InputStream inputStream = null;
    private static Socket socket;
    public static Handler childHandler;
    //    private boolean RxFlag = false;
    static final int rxExit = 11;
    static final int txData = 10;
    private String strIPAddressed;
    private String orderMessage;
    int sendReceiveIdentifying = 1;
    int sendReceive;
    private RxThread rxThread;
    private sendThread sendthread;
    public static boolean nbtstat;
    private static ClientThread clientThread;

    //接收到的指令
    public static String orderMessageReceive;

    //未用到的参数(不知道干嘛的)
    Context mainContext;
    Message msg;
    int getlength = 0, getlenth_temp;
    int ucRecvLen = 7;
    byte tempdate[] = new byte[20];

    private ClientThread()
    {

    }
    public static ClientThread getInstance()
    {
        clientThread = null;
        if (clientThread == null)
        {
            synchronized (ClientThread.class)
            {
                if (clientThread == null)
                {
                    clientThread = new ClientThread();
                }
            }
        }
        return clientThread;
    }

    //接收数据
    public void receiveOrderMsg()
    {
        sendReceive =1;
    }

    //发送数据
    public void sendOrderMsg(String OrderMsg)
    {
        sendReceive = 2;
        orderMessage = OrderMsg;
    }

    @Override
    public void run()
    {
//        XLog.e("SOCKET","进入连接方法");
        SocketAddress socketAddressed = new InetSocketAddress(Constants.wifiIpAddressed, Constants.comPort);
        //判断当前连接状态
        if (socket == null || !socket.isConnected())
        {
            socket = new Socket();

            try
            {
                socket.connect(socketAddressed, Constants.comPort);
                XLog.e("SOCKET", "outputStream = " + outputStream);
                nbtstat = true;
//                XLog.e("SOCKET", "连接服务器成功");
            }
            catch (IOException e)
            {
//                XLog.e("SOCKET", "连接服务器失败");
                e.printStackTrace();
            }
            
        }
        try
        {
            inputStream = socket.getInputStream();
            outputStream = socket.getOutputStream();
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        RefreshDataUtils.getRefreshDataUtils().setData(Constants.BED_WIFE, nbtstat + "");
        if (sendReceive == 1)
        {
//            XLog.e("SOCKET","接收数据");
            rxThread = new RxThread();
            rxThread.start();
        }
        else if (sendReceive == 2)
        {
//            XLog.e("SOCKET","发送数据");
            sendthread = new sendThread();
            sendthread.start();
        }
    }


    // 接收数据线程
    public class RxThread extends Thread
    {
        public void run()
        {
            try
            {
                while (socket.isConnected()) {
                    byte strRxBuf[] = new byte[23];
                    // byte i;
                    int RxIndex, len = 0, readBytes = 0;
                    if (inputStream != null)
                    {
                        len = inputStream.read(strRxBuf);
                    }
                    if (len > 0)
                    {
                        byte buffer[] = new byte[len];
                        for (int i = 0; i < len; i++)
                        {
                            buffer[i] = strRxBuf[i];
                        }

                        Log.e("strRead1 ==", bytesToHexString(buffer));
                        Log.e("strRead2 ==", "" + buffer);
                        Log.e("len ==", len + "");
//                        XLog.e("SOCKET", "接收到数据");
                        orderMessageReceive = bytesToHexString(buffer).toUpperCase();
                        OrderMsgExecute.orderMsgScreen(orderMessageReceive);
                    }
                    else
                    {
                        // 连接断开
                        nbtstat = false;
                        RefreshDataUtils.getRefreshDataUtils().setData(Constants.BED_WIFE, nbtstat + "");
                    }
                }
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }

    // 发送数据线程
    public class sendThread extends Thread
    {
        public void run()
        {
            try
            {
                String senddata = ClientThread.this.orderMessage;
                int length = senddata.length();
                byte[] result = new byte[23];
                result = hexStringToBytes(orderMessage);
                if (outputStream != null)
                {
                    outputStream.write(result);
                }
            }
            catch (IOException e)
            {
//                XLog.e("SOCKET","指令出错");
                e.printStackTrace();
            }
        }
    }

    //String转byte[]
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    //byte[]转String
    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    public static void releaseLastSocket() {
        try
        {
            if (socket != null)
            {
                if (socket.isConnected())
                {
                    socket.close();
                    XLog.e("SOCKET","静态方法关闭当前连接");
                    socket = new Socket();
                }
            }
            else
            {
                socket = new Socket();
            }

        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
}
